#define  _CRT_SECURE_NO_WARNINGS
#include "SepList.h"

void SLInit(SL* ps)
{
	ps->arr = (SLDatetType*)malloc(4 * sizeof(SLDatetType*));
	if (ps->arr == NULL)
	{
		perror("malloc failed");
		exit(-1);
	}
	ps->size = 0;
	ps->capacity = 4;
}

void SLDestory(SL* ps)
{
	free(ps->arr);
	ps->arr = NULL;
	ps->capacity = ps->size = 0;
}

void SLPrint(const SL* ps)
{
	for (int i = 0; i < ps->size; i++)
	{
		printf("%d ", ps->arr[i]);
	}
	printf("\n");
}

void SLCheckCapacity(SL* ps)
{
	if (ps->capacity == ps->size)
	{
		SLDatetType* tmp = (SLDatetType*)realloc(ps->arr, ps->capacity * 2 * (sizeof(SLDatetType)));
		if (tmp == NULL)
		{
			perror("realloc failed");
			exit(-1);
		}
		ps->arr = tmp;
		ps->capacity *= 2;
	}
}

//void SLInit(SL* ps)
//{
//	ps->arr = NULL;
//	ps->size = ps->capacity = 0;
//}
// 
//void SLCheckCapacity(SL* ps)
//{
//	if (ps->capacity == ps->size)
//	{
//		int newcapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
//		SLDatetType* tmp = (SLDatetType*)realloc(ps->arr, newcapacity * 2 * (sizeof(SLDatetType)));
//		if (tmp == NULL)
//		{
//			perror("realloc failed");
//			exit(-1);
//		}
//		ps->arr = tmp;
//		ps->capacity = newcapacity;
//	}
//
//}

void SLPushBack(SL* ps, SLDatetType x)
{
	assert(ps);
	SLCheckCapacity(ps);

	ps->arr[ps->size] = x;
	ps->size++;
}

void SLPopBack(SL* ps)
{
	assert(ps);
	assert(ps->size > 0);
	ps->size--;
}

void SLPushFront(SL* ps, SLDatetType x)
{
	assert(ps);
	SLCheckCapacity(ps);
	for (int i = ps->size; i > 0; i--)
	{
		ps->arr[i] = ps->arr[i - 1];
	}
	ps->arr[0] = x;
	ps->size++;
}

void SLPopFront(SL* ps)
{
	assert(ps);
	assert(ps->size);
	for (int i = 0; i < ps->size -1 ; i++)
	{
		ps->arr[i] = ps->arr[i + 1];
	}
	ps->size--;
}

void SLInsert(SL* ps, int pos, SLDatetType x)
{
	assert(ps);
	assert(pos >= 0 && pos <= ps->size);
	for (int i = ps->size; i > pos; i--)
	{
		ps->arr[i] = ps->arr[i - 1];
	}
	ps->arr[pos] = x;
	ps->size++;
}

void SLErase(SL* ps, int pos)
{
	assert(ps);
	assert(pos >= 0 && pos < ps->size);
	for(int i=pos; i<ps->size-1; i++)
	{
		ps->arr[i] = ps->arr[i + 1];
	}
	ps->size--;
}

int SLFind(SL* ps, SLDatetType x)
{
	assert(ps);
	for (int i = 0; i < ps->size; i++)
	{
		if (ps->arr[i] == x)
			return i;
	}
	return -1;
}

void SLModify(SL* ps, int pos, SLDatetType x)
{
	assert(ps);
	assert(pos >= 0 && pos < ps->size);
	ps->arr[pos] = x;
}